package com.lanchetech.admin.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.admin.service.FarmService;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.*;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.common.enums.FarmProductTypeEnum;
import com.lanchetech.common.enums.LogisticsStatusEnum;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FarmServiceImpl implements FarmService {

    @Autowired
    MailboxMapper mailboxMapper;

    @Autowired
    FarmUserMapper farmUserMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    TreeMapper treeMapper;

    @Autowired
    CowMapper cowMapper;

    @Autowired
    SaplingMapper saplingMapper;

    @Autowired
    FarmProductMapper farmProductMapper;

    @Autowired
    FarmOrderMapper farmOrderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserAddressMapper userAddressMapper;

    @Autowired
    GrassFlowMapper grassFlowMapper;

    @Autowired
    WaterFlowMapper waterFlowMapper;

    @Autowired
    FarmTaskMapper farmTaskMapper;

    @Override
    public ResultData<BasePageResp<Mailbox>> getMailBoxPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Mailbox> list = mailboxMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editMailBox(Mailbox mailbox) {
        if (mailbox.getId() == null) {
            mailbox.setCreatedAt(new Date());
            mailbox.setUpdatedAt(new Date());
            mailboxMapper.insert(mailbox);
        } else {
            mailbox.setUpdatedAt(new Date());
            mailboxMapper.updateByPrimaryKeySelective(mailbox);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<Mailbox> getMailBoxDetail(Long id) {
        Mailbox mailbox = mailboxMapper.selectByPrimaryKey(id);
        return new ResultData<>(mailbox);
    }

    @Override
    public BaseResp deleteMailBox(Long id) {
        mailboxMapper.deleteByPrimaryKey(id);
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<GrassFlowVO>> getGrassFlowPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<GrassFlowVO> list = grassFlowMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(GrassFlowVO::getUserId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<WaterFlowVO>> getWaterFlowPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<WaterFlowVO> list = waterFlowMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(WaterFlowVO::getUserId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<FarmUserListVO>> getFarmUserPage(PageReq req) {

        if(!StringUtils.isEmpty(req.getNickname())){
            User user = userMapper.findOneByNicknameLike(req.getNickname());
            req.setUserId(user == null ? 0L : user.getId());
        }

        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<FarmUserListVO> list = farmUserMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(FarmUserListVO::getUserId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<FarmProduct>> getFarmProductPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<FarmProduct> list = farmProductMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editFarmProduct(FarmProduct farmProduct) {
        if(FarmProductTypeEnum.TREE.equals(farmProduct.getType())){
            farmProduct.setMilk(new BigDecimal(BigInteger.ZERO));
        }
        if (farmProduct.getId() == null) {
            farmProduct.setSales(0);
            farmProduct.setCreatedAt(new Date());
            farmProduct.setUpdatedAt(new Date());
            farmProduct.setDeleted(DeletedEnum.DEFAULT.getStatus());
            farmProductMapper.insert(farmProduct);
        } else {
            farmProduct.setUpdatedAt(new Date());
            farmProductMapper.updateByPrimaryKeySelective(farmProduct);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<FarmProduct> getFarmProductDetail(Long id) {
        FarmProduct farmProduct = farmProductMapper.selectByPrimaryKey(id);
        if (DeletedEnum.DEFAULT.getStatus().equals(farmProduct.getDeleted())) {
            return new ResultData<>(farmProduct);
        }
        return new ResultData<>();
    }

    @Override
    public BaseResp deleteFarmProduct(Long id) {
        FarmProduct selectFarmProduct = farmProductMapper.selectByPrimaryKey(id);
        if (DeletedEnum.DEFAULT.getStatus().equals(selectFarmProduct.getDeleted())) {
            farmProductMapper.updateDeletedById(DeletedEnum.DELETED.getStatus(), id);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<FarmOrderVO>> getFarmProductOrderPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<FarmOrderVO> list = farmOrderMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(FarmOrderVO::getUserId).collect(Collectors.toList()));
            Map<Long, FarmProduct> farmProductMap = daoService.getFarmProductMap(list.stream().map(FarmOrderVO::getFarmProductId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setFarmProductName(farmProductMap.get(item.getFarmProductId()).getName());
                item.setFarmProductMainImage(farmProductMap.get(item.getFarmProductId()).getMainImage());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editFarmOrderLogistics(FarmOrder req) {
        FarmOrder farmOrder = farmOrderMapper.selectByPrimaryKey(req.getId());
        farmOrder.setLogisticsCompany(req.getLogisticsCompany());
        farmOrder.setLogisticsNumber(req.getLogisticsNumber());
        farmOrder.setLogisticsStatus(LogisticsStatusEnum.DONE.getStatus());
        farmOrder.setUpdatedAt(new Date());
        farmOrder.setDeliveryTime(new Date());
        farmOrderMapper.updateByPrimaryKeySelective(farmOrder);
        return new BaseResp();
    }

    @Override
    public ResultData<FarmOrderVO> getFarmProductOrderDetail(Long id) {
        FarmOrder selectFarmOrder = farmOrderMapper.selectByPrimaryKey(id);
        FarmOrderVO vo = new FarmOrderVO();
        BeanUtils.copyProperties(selectFarmOrder, vo);
        User user = userMapper.selectByPrimaryKey(selectFarmOrder.getUserId());
        FarmProduct farmProduct = farmProductMapper.selectByPrimaryKey(selectFarmOrder.getFarmProductId());
        vo.setUserAddress(userAddressMapper.selectByPrimaryKey(vo.getUserAddressId()));
        vo.setUserNickname(user.getNickname());
        vo.setUserAvatar(user.getAvatar());
        vo.setFarmProductName(farmProduct.getName());
        vo.setFarmProductMainImage(farmProduct.getMainImage());
        vo.setOriginalPrice(farmProduct.getOriginalPrice());
        return new ResultData<>(vo);
    }

    @Override
    public ResultData<BasePageResp<UserCowListVO>> getUserCowPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<UserCowListVO> list = cowMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(UserCowListVO::getUserId).collect(Collectors.toList()));
            Map<Long,FarmUser>  farmUserMap = daoService.getFarmUserMap(list.stream().map(UserCowListVO::getUserId).collect(Collectors.toList()));
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setCowLevel(farmUserMap.get(item.getUserId()).getCowLevel());
                item.setGrass(farmUserMap.get(item.getUserId()).getGrass());
                item.setCurrentMilk(farmUserMap.get(item.getUserId()).getCurrentMilk());
                item.setHistoryMilk(farmUserMap.get(item.getUserId()).getHistoryMilk());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<UserTreeListVO>> getUserTreePage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<UserTreeListVO> list = treeMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(UserTreeListVO::getUserId).collect(Collectors.toList()));
            Map<Long, Sapling> saplingMap = daoService.getSaplingMap();
            list.stream().forEach(item -> {
                item.setUserNickname(userMap.get(item.getUserId()).getNickname());
                item.setUserAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setSaplingName(saplingMap.get(item.getSaplingId()).getName());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editSaplingConfig(Sapling sapling) {
        if (sapling.getId() == null) {
            sapling.setSales(0);
            sapling.setCreatedAt(new Date());
            sapling.setUpdatedAt(new Date());
            saplingMapper.insert(sapling);
        } else {
            sapling.setUpdatedAt(new Date());
            saplingMapper.updateByPrimaryKeySelective(sapling);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<Sapling>> getSaplingPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Sapling> list = saplingMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<Sapling> getSaplingDetail(Long id) {
        Sapling sapling = saplingMapper.selectByPrimaryKey(id);
        return new ResultData<>(sapling);
    }

    @Override
    public ResultData<BasePageResp<FarmTask>> getFarmTaskPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<FarmTask> list = farmTaskMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editFarmTask(FarmTask farmTask) {
        if (farmTask.getId() == null) {
            farmTask.setSales(0);
            farmTask.setCreatedAt(new Date());
            farmTask.setUpdatedAt(new Date());
            farmTaskMapper.insert(farmTask);
        } else {
            farmTask.setUpdatedAt(new Date());
            farmTaskMapper.updateByPrimaryKeySelective(farmTask);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<FarmTask> getFarmTaskDetail(Long id) {
        FarmTask farmTask = farmTaskMapper.selectByPrimaryKey(id);
        return new ResultData<>(farmTask);
    }

    @Override
    public BaseResp deleteFarmTask(Long id) {
        farmTaskMapper.deleteByPrimaryKey(id);
        return new BaseResp();
    }
}
